package sg.edu.nus.iss.pacman.form;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import sg.edu.nus.iss.pacman.dao.Maze;
import sg.edu.nus.iss.pacman.midlet.PacManMIDlet;

/**
 * This is a screen for user to select a maze which will be used in the game.
 * 
 * @author Daniel
 *
 */
public class SelectMazeList extends List implements CommandListener {

	private static final String TITLE = "Select a Map";
	private PacManMIDlet mainApp;
	
	private Command cmdBack;
	private Command cmdSelect;
	
	private Maze[] listMaze;
	
	/**
	 * Constructor
	 * @param mainApp PacManMIDlet
	 * @param listMaze list of available mazes
	 */
	public SelectMazeList(PacManMIDlet mainApp, Maze[] listMaze) {
		super(TITLE, List.IMPLICIT, new String[]{}, null);
		this.mainApp = mainApp;
		this.listMaze = listMaze;
		init();
	}
	
	/**
	 * Initializes the screen
	 */
	private void init() {
		cmdBack = new Command(PacManMIDlet.LABEL_CMD_BACK, Command.EXIT, 1);
		cmdSelect = new Command(PacManMIDlet.LABEL_CMD_SELECT, Command.OK, 1);
		
		for (int i=0; i<listMaze.length; i++) {
			Maze maze = listMaze[i];
			insert(i, maze.getMazeName(), null);
		}
		
		addCommand(cmdBack);
		addCommand(cmdSelect);
		setCommandListener(this);
	}
	
	/**
	 * This is a method which handles the command actions
	 */
	public void commandAction(Command cmd, Displayable disp) {
		if (cmd == cmdBack) {
			mainApp.displayMainMenu();
		} else if (cmd == cmdSelect) {
			int idx = getSelectedIndex();
			
			if (idx >= 0) {
				mainApp.launchGame(listMaze[idx]);	
			}
			
			
		}
 	}

}
